package org.gwt.pluginframework.plugin;

import org.gwt.pluginframework.common.Plugin;
import org.gwt.pluginframework.common.event.CommonEvents;
import org.gwt.pluginframework.common.event.IPluginEvent;
import org.gwt.pluginframework.common.event.PluginEventHandler;

import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;

public class ExceptionHandlingPlugin extends Plugin {
	private static final long serialVersionUID = -5569735083796495578L;

	protected Window window;

	public void setupManifest() {
		manifest.setName("ExceptionHandlingPlugin");
		manifest.setVersion("1.0");
	}
	
	@Override
	public void onInitialize() {
		registerEventHandler(new PluginEventHandler(CommonEvents.EXCEPTION_EVENT){
			public void handle(IPluginEvent event) {
				Window window = new Window();
				window.setWidth(600);
				window.setHeight(400);
				window.setHeading("Exception occured!");
				window.setLayout(new FitLayout());
				TextArea textArea = new TextArea();
				window.add(textArea);
				
				StringBuffer buffer = new StringBuffer();
				
				appendException((Exception) event.getParameters().get(CommonEvents.EXCEPTION_PARAMETER), buffer);
				
				textArea.setValue(buffer.toString());
				window.show();
			}
		});
	}
	
	protected void appendException(Throwable t, StringBuffer buffer) {
		if(t == null) { 
			return;
		}
		buffer.append(t.getMessage() + "\n");
		for(StackTraceElement e : t.getStackTrace()) {
			buffer.append("   " + e + "\n");
		}
		if(t.getCause() != null && t.getCause() != t) {
			appendException(t.getCause(), buffer);
		}
	}
}
